/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * File Name          : freertos.c
  * Description        : Code for freertos applications
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under Ultimate Liberty license
  * SLA0044, the "License"; You may not use this file except in compliance with
  * the License. You may obtain a copy of the License at:
  *                             www.st.com/SLA0044
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "usart.h"
#include "queue.h"
#include "ad7606.h"
#include "arm_math.h"
#include "arm_const_structs.h"
#include "EventRecorder.h"
#include <stdlib.h>
#include "sram.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef struct{
    uint8_t cmd;
    uint8_t chl;
    uint16_t size;
}ADC_READBUFF_PARA_TYPE;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

#define SAMPLING_POINTS  4096
#define SAMPLING_CHANNEL 6  // Ua Ub Uc Ia Ib Ic

#define UA_CHANNEL      0
#define UB_CHANNEL      1
#define UC_CHANNEL      2
#define IA_CHANNEL      3
#define IB_CHANNEL      4
#define IC_CHANNEL      5


#define TEST_LENGTH_SAMPLES 4096

#define ADC_CTRL    ( 1 << 0 )

#define ADC_BUFF_SIZE		(SAMPLING_POINTS*SAMPLING_CHANNEL)

float32_t adcTrueBuff[SAMPLING_CHANNEL][SAMPLING_POINTS] __attribute__((section("EXRAM")));
float32_t adcReadBuff[SAMPLING_CHANNEL][SAMPLING_POINTS] __attribute__((section("EXRAM")));

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */
volatile uint8_t  isFreeRTOSSysOn = 0;
volatile uint32_t osRuntimeCounter;
volatile uint32_t adcNumPoints = 0;


/* USER CODE END Variables */
/* Definitions for adcReadTask */
osThreadId_t adcReadTaskHandle;
const osThreadAttr_t adcReadTask_attributes = {
  .name = "adcReadTask",
  .priority = (osPriority_t) osPriorityNormal1,
  .stack_size = 256 * 4
};
/* Definitions for usartRxTask */
osThreadId_t usartRxTaskHandle;
const osThreadAttr_t usartRxTask_attributes = {
  .name = "usartRxTask",
  .priority = (osPriority_t) osPriorityNormal,
  .stack_size = 256 * 4
};
/* Definitions for idleTask */
osThreadId_t idleTaskHandle;
const osThreadAttr_t idleTask_attributes = {
  .name = "idleTask",
  .priority = (osPriority_t) osPriorityLow,
  .stack_size = 256 * 4
};
/* Definitions for usartRxMsgQueue */
osMessageQueueId_t usartRxMsgQueueHandle;
const osMessageQueueAttr_t usartRxMsgQueue_attributes = {
  .name = "usartRxMsgQueue"
};
/* Definitions for adcReadMsgQueue */
osMessageQueueId_t adcReadMsgQueueHandle;
const osMessageQueueAttr_t adcReadMsgQueue_attributes = {
  .name = "adcReadMsgQueue"
};
/* Definitions for usartMutex */
osMutexId_t usartMutexHandle;
const osMutexAttr_t usartMutex_attributes = {
  .name = "usartMutex"
};
/* Definitions for adcSamplingBuffMutex */
osMutexId_t adcSamplingBuffMutexHandle;
const osMutexAttr_t adcSamplingBuffMutex_attributes = {
  .name = "adcSamplingBuffMutex"
};
/* Definitions for adcReadBuffMutex */
osMutexId_t adcReadBuffMutexHandle;
const osMutexAttr_t adcReadBuffMutex_attributes = {
  .name = "adcReadBuffMutex"
};
/* Definitions for adcFinishedBinSem */
osSemaphoreId_t adcFinishedBinSemHandle;
const osSemaphoreAttr_t adcFinishedBinSem_attributes = {
  .name = "adcFinishedBinSem"
};

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */

/* USER CODE END FunctionPrototypes */

void StartDefaultTask(void *argument);
void usartRxFunc(void *argument);
void adcReadFunc(void *argument);

void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */

/* Hook prototypes */
void configureTimerForRunTimeStats(void);
unsigned long getRunTimeCounterValue(void);
void vApplicationStackOverflowHook(xTaskHandle xTask, signed char *pcTaskName);
void vApplicationMallocFailedHook(void);

/* USER CODE BEGIN 1 */
/* Functions needed when configGENERATE_RUN_TIME_STATS is on */
__weak void configureTimerForRunTimeStats(void)
{
    osRuntimeCounter = 0;
}

__weak unsigned long getRunTimeCounterValue(void)
{
    return osRuntimeCounter;
}


/* USER CODE END 1 */

/* USER CODE BEGIN 4 */
void vApplicationStackOverflowHook(xTaskHandle xTask, signed char *pcTaskName)
{
   /* Run time stack overflow checking is performed if
   configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook function is
   called if a stack overflow is detected. */
    
    msgPrintf("#[error_msg]: Task Stack Overflow Hook exception occurs: %s\r\n",pcTaskName);
    __set_PRIMASK(1);
    while(1);
}
/* USER CODE END 4 */

/* USER CODE BEGIN 5 */
void vApplicationMallocFailedHook(void)
{
   /* vApplicationMallocFailedHook() will only be called if
   configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hook
   function that will get called if a call to pvPortMalloc() fails.
   pvPortMalloc() is called internally by the kernel whenever a task, queue,
   timer or semaphore is created. It is also called by various parts of the
   demo application. If heap_1.c or heap_2.c are used, then the size of the
   heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
   FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
   to query the size of free heap space that remains (although it does not
   provide information on how the remaining heap might be fragmented). */
   msgPrintf("#[error_msg]: Application Malloc Failed exception occurs\r\n");
   __set_PRIMASK(1);
   while(1);
}
/* USER CODE END 5 */

/**
  * @brief  FreeRTOS initialization
  * @param  None
  * @retval None
  */
void MX_FREERTOS_Init(void) {
  /* USER CODE BEGIN Init */

  /* USER CODE END Init */
  /* Create the mutex(es) */
  /* creation of usartMutex */
  usartMutexHandle = osMutexNew(&usartMutex_attributes);

  /* creation of adcSamplingBuffMutex */
  adcSamplingBuffMutexHandle = osMutexNew(&adcSamplingBuffMutex_attributes);

  /* creation of adcReadBuffMutex */
  adcReadBuffMutexHandle = osMutexNew(&adcReadBuffMutex_attributes);

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* Create the semaphores(s) */
  /* creation of adcFinishedBinSem */
  adcFinishedBinSemHandle = osSemaphoreNew(1, 0, &adcFinishedBinSem_attributes);

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  /* add semaphores, ... */
  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
  /* USER CODE END RTOS_TIMERS */

  /* Create the queue(s) */
  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  adcReadMsgQueueHandle = osMessageQueueNew(2, sizeof(ADC_READBUFF_PARA_TYPE), &adcReadMsgQueue_attributes);
  usartRxMsgQueueHandle = osMessageQueueNew(2, sizeof(USART_RECEIVETYPE), &usartRxMsgQueue_attributes);
  /* USER CODE END RTOS_QUEUES */

  /* Create the thread(s) */
  /* creation of idleTask */
  idleTaskHandle = osThreadNew(StartDefaultTask, NULL, &idleTask_attributes);

  /* creation of usartRxTask */
  usartRxTaskHandle = osThreadNew(usartRxFunc, NULL, &usartRxTask_attributes);

  /* creation of adcReadTask */
  adcReadTaskHandle = osThreadNew(adcReadFunc, NULL, &adcReadTask_attributes);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

  /* USER CODE BEGIN RTOS_EVENTS */
  /* add events, ... */

  EventRecorderInitialize(EventRecordAll, 1U);
  EventRecorderStart();
  
  isFreeRTOSSysOn = 1;
  msgPrintf("RTOS init success, wait kernel start...\r\n\r\n");
  /* USER CODE END RTOS_EVENTS */

}

/* USER CODE BEGIN Header_StartDefaultTask */
/**
  * @brief  Function implementing the idleTask thread.
  * @param  argument: Not used
  * @retval None
  */
/* USER CODE END Header_StartDefaultTask */
void StartDefaultTask(void *argument)
{
  /* USER CODE BEGIN StartDefaultTask */
  /* Infinite loop */
  msgPrintf("task defaultTask start\r\n");
  for(;;)
  {
    osDelay(1);
  }
  /* USER CODE END StartDefaultTask */
}

/* USER CODE BEGIN Header_usartRxFunc */
/**
* @brief Function implementing the usartRxTask thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_usartRxFunc */
void usartRxFunc(void *argument)
{
  /* USER CODE BEGIN usartRxFunc */
  /* Infinite loop */
  USART_RECEIVETYPE pUARTRx ;
  char *pBuff = NULL;
  ADC_READBUFF_PARA_TYPE adcReadParam;
  msgPrintf("task usartRxFunc start\r\n");
  for(;;)
  {
    osMessageQueueGet(usartRxMsgQueueHandle, (void*)&pUARTRx,NULL,osWaitForever);
    msgPrintf("usartRx :%s\r\n",pUARTRx.RxBuff);
    
    /*! ps command handle */
    if (memcmp( pUARTRx.RxBuff, "ps", 2) == 0) {
        pBuff = (char*)pvPortMalloc(300);
        if (pBuff != NULL) {
            memset(pBuff, 0, 300);
            msgPrintf("taskName\t\ttaskState\tpriority\trestStack\ttaskID\r\n" );
            vTaskList(pBuff);
            msgPrintf("%s\r\n",pBuff);
            msgPrintf("X : Running, B : Blocked, R : Ready, D : Deleted, S : Suspended\r\n");
            vPortFree(pBuff);
        }
    }
    /*! ts command handle */
    else if (memcmp( pUARTRx.RxBuff, "ts", 2 ) == 0) {
        pBuff = (char*)pvPortMalloc(300);
        if (pBuff != NULL){
            memset(pBuff, 0, 300);
            msgPrintf("taskName\t\trunCount\t\tuseRate\r\n");
            vTaskGetRunTimeStats(pBuff);
            msgPrintf("%s\r\n", pBuff);
            vPortFree(pBuff);
        }
    }
    /*! adcon command handle */
    else if (memcmp( pUARTRx.RxBuff, "adcon", 5 ) == 0) {
            AD7606Init();
            AD7606Start();
            msgPrintf("AD7606 start\r\n");
    }
    /*! adcoff command handle */
    else if( memcmp( pUARTRx.RxBuff, "adcoff", 6 ) == 0){
            AD7606Stop();
            msgPrintf("AD7606 stop\r\n");
    }
    
    /*! adc read cmd: adcread,X,Y  X=0~7,Y = num e.g. adcread,1,100 */
    else if( memcmp( pUARTRx.RxBuff, "adcread,", 8 ) == 0){
        adcReadParam.cmd = 1;
        adcReadParam.chl = *(pUARTRx.RxBuff + 8) - '0';
        adcReadParam.size = atoi( (const char*)(pUARTRx.RxBuff + 10) );
        if(adcReadParam.size > 0 && adcReadParam.size <= SAMPLING_POINTS){
            osMessageQueuePut(adcReadMsgQueueHandle,&adcReadParam,1,0);
        }
    }
    
  }
  /* USER CODE END usartRxFunc */
}

/* USER CODE BEGIN Header_adcReadFunc */
/**
* @brief Function implementing the adcReadTask thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_adcReadFunc */
void adcReadFunc(void *argument)
{
  /* USER CODE BEGIN adcReadFunc */
  /* Infinite loop */
  ADC_READBUFF_PARA_TYPE adcReadParam;
  uint16_t adcReadIdex;
  msgPrintf("task adcReadFunc start\r\n");
  for(;;)
  {
    /*! wait pc adc cmd */
    osMessageQueueGet(adcReadMsgQueueHandle,(void*)&adcReadParam,NULL,osWaitForever);
    msgPrintf("run adcReadFunc...\r\n");
    if(adcReadParam.cmd == 1){
      
        osMutexAcquire(adcReadBuffMutexHandle,osWaitForever);
        {
            for(adcReadIdex = 0; adcReadIdex < adcReadParam.size; adcReadIdex++){
                msgPrintf("%1.5f\r\n",AD7606ConvValue(adcReadBuff[adcReadIdex][adcReadParam.chl]));
            }
        }
        osMutexRelease(adcReadBuffMutexHandle);
    
        msgPrintf("\r\n");
    }
    osThreadYield();
  }
  /* USER CODE END adcReadFunc */
}

/* Private application code --------------------------------------------------*/
/* USER CODE BEGIN Application */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if (GPIO_Pin == AD7606Irq_Pin){
        if (adcNumPoints < SAMPLING_POINTS){
            /*! read SAMPLING_CHANNEL from adc7606 buff */
            uint16_t adc7606Buff[SAMPLING_CHANNEL];
            AD7606BusyIrqCallback(adc7606Buff, SAMPLING_CHANNEL);
            
            /*! convert adc true value */
            osMutexAcquire(adcSamplingBuffMutexHandle,osWaitForever);
            for (int idx_channel = 0; idx_channel < SAMPLING_CHANNEL; ++idx_channel){
                adcTrueBuff[idx_channel][adcNumPoints] = AD7606ConvValue(adc7606Buff[idx_channel]);
            }
            osMutexRelease(adcSamplingBuffMutexHandle);
            
            adcNumPoints++;
            
            /*! sampling frame finished */
            if (adcNumPoints == SAMPLING_POINTS){
                adcNumPoints = 0;
                osSemaphoreRelease(adcFinishedBinSemHandle);
            }
        }
    }
}

 /**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM1 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM1) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */
  if (htim->Instance == TIM6) {
    osRuntimeCounter++;
  }
  /* USER CODE END Callback 1 */
}

/* USER CODE END Application */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
